package com.star.robot.service;

import com.star.robot.constant.Constant;
import com.star.robot.dto.*;
import com.star.robot.entity.Company;
import com.star.robot.entity.DtArea;
import com.star.robot.entity.Team;
import com.star.robot.entity.TeamMember;
import com.star.robot.enums.CompanyTypeEnum;
import com.star.robot.repository.CompanyRepository;
import com.star.robot.repository.TeamMemberRepository;
import com.star.robot.repository.TeamRepository;
import com.star.robot.repository.DtAreaRepositoty;
import com.star.robot.specialficaition.TeamMemberSpecial;
import com.star.robot.specialficaition.TeamSpecial;
import com.star.robot.util.ExportExcel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExportService {

    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private TeamRepository teamRepository;
    @Autowired
    private TeamMemberRepository teamMemberRepository;

    @Autowired
    private DtAreaRepositoty dtAreaRepositoty;

    private final String scoreMoban = "成绩导入模版";
    private final String teamMemberMoban = "队员信息";

    private final String titleName = scoreMoban;

    @Autowired
    private TeamSpecial teamSpecial;

    @Autowired
    private EntityManager entityManager;

    @Autowired
    private TeamMemberSpecial teamMemberSpecial;


    /**
     * 生成成绩模版xls
     * @return
     * @param lunci
     */
    public String exportScore(Integer lunci ,TeamBackendQueryDto requestDto ){

        if (lunci == null) {
            lunci = 1;
        }


        String [] headers = new String[]{ "参赛项目","组别","队伍ID" , "单位性质" , "单位名称" , "队伍名称" , "轮次" , "成绩"};

        List<ExportScoreDto> exportScoreDtos = new ArrayList<>();
        Pageable page = new PageRequest(0, Integer.MAX_VALUE);

        Page<Team> pageable = teamSpecial.findByRequestDto(page , requestDto);
//        List<Company> companies = companyRepository.findAll();
//        if(!CollectionUtils.isEmpty(companies)) {
//            for (Company company : companies) {

//                String companyTypeStr = getCompanyTypeStr(company.getCompanyType());
//                List<Team> teams = company.getTeams();
                if (!CollectionUtils.isEmpty(pageable.getContent())) {
                    for (Team team : pageable.getContent()) {
                        ExportScoreDto exportScoreDto = ExportScoreDto.builder()
                                .projectName(team.getProject().getName())
                                .projectClass(team.getProjectClassEnum().getName())
                                .teamId(team.getId())
                                .companyType(team.getCompany().getCompanyType().getName())
                                .companyName(team.getCompany().getName())
                                .teamName(team.getTeamName())
                                .lunci(lunci)
                                .build();
                        exportScoreDtos.add(exportScoreDto);
                    }
                }

//            }
//        }

        String fileName = System.currentTimeMillis()+".xls";
        ExportExcel.exportExcel(scoreMoban, titleName , headers  , exportScoreDtos , Constant.downloadPath+"/"+fileName,  null);
        return fileName;
    }

    /**
     * 导出队员xls
     * @return
     */
    public String exportTeamMember(HttpServletRequest request, TeamMemberQueryDto requestDto){
        String [] headers = new String[]{ "队员姓名" , "单位性质" , "单位名称" , "队伍名称" , "参赛类别" , "组别","性别","身份证号","队服尺码","所属学校"};

        List<ExportTeamMembersDto> exportTeamMembersDtos = new ArrayList<>();


//        SimpleJpaRepository simpleJpaRepository = new SimpleJpaRepository<TeamMember,Long>(TeamMember.class , entityManager);
        List<TeamMember> teamMemberList = teamMemberSpecial.findByRequest(requestDto,request);


        for (TeamMember teamMember : teamMemberList) {
            //预先去除懒加载
            Team team = teamMember.getTeam();
            Company company = team.getCompany();
            ExportTeamMembersDto exportTeamMembersDto = ExportTeamMembersDto.builder()
                    .name(teamMember.getName())
                    .companyType(company.getCompanyType().getName())
                    .companyName(company.getName())
                    .teamName(team.getTeamName())
                    .projectName(team.getProject() != null ? team.getProject().getName() : null)
                    .projectClass(team.getProjectClassEnum().getName())
                    .sex(teamMember.getSex()== 1 ?  "男":"女")
                    .idCard(teamMember.getIdCard())
                    .size(teamMember.getSize().getName())
                    .school(company.getName())
                    .build();
            exportTeamMembersDtos.add(exportTeamMembersDto);

        }



        String fileName = System.currentTimeMillis()+"队员信息.xls";
        ExportExcel.exportExcel(teamMemberMoban, teamMemberMoban , headers  , exportTeamMembersDtos , Constant.downloadPath+"/"+fileName,  null);
        return fileName;
    }
    public String getCompanyTypeStr(CompanyTypeEnum companyTypeEnum){
        return companyTypeEnum.getName();
    }
    /**
     * 生成队伍xls
     * @return
     */
    public String exportTeam(TeamBackendQueryDto requestDto){
        String [] headers = new String[]{ "所在地区" , "单位性质" ,"单位名称" ,  "队伍名称" , "参赛项目","组别" , "辅导老师1姓名" , "辅导老师1电话" , "辅导老师2姓名" , "辅导老师2电话"};

        List<TeamDownloadDto> teamRespDtos = new ArrayList<>();

        PageRequest pageRequest = new PageRequest(0 , Integer.MAX_VALUE);
        Page<Team> teamIterable = teamSpecial.findByRequestDto(pageRequest , requestDto);

        for(Team team :teamIterable.getContent()) {
            DtArea dtArea3 = null;

            if (!StringUtils.isEmpty(team.getCompany().getCityId())) {
                dtArea3 = dtAreaRepositoty.findByid(Long.valueOf(team.getCompany().getCityId()));
            }
            String areaName = null;
            if(dtArea3 != null){
                areaName = dtArea3.getAreaName();
            }
            TeamRespDto teamRespDto = TeamRespDto.builder()
                    .areaName(areaName)
                    .companyType(team.getCompany().getCompanyType().getName())
                    .companyName(team.getCompany().getName())
                    .teamName(team.getTeamName())
                    .teamType(team.getProjectClassEnum() != null ?team.getProjectClassEnum().getName() : null)
                    .projectName( team.getProject() != null ? team.getProject().getName() : null)
                    .build();

            if(team.getTeamLeaders() != null && team.getTeamLeaders().size() == 1 ){
                teamRespDto.setLeader1Name(team.getTeamLeaders().get(0).getName());
                teamRespDto.setLeader1Phone(team.getTeamLeaders().get(0).getPhone());

            }
            if(team.getTeamLeaders() != null && team.getTeamLeaders().size() == 2 ){
                teamRespDto.setLeader1Name(team.getTeamLeaders().get(0).getName());
                teamRespDto.setLeader1Phone(team.getTeamLeaders().get(0).getPhone());
                teamRespDto.setLeader2Name(team.getTeamLeaders().get(1).getName());
                teamRespDto.setLeader2Phone(team.getTeamLeaders().get(1).getPhone());
            }
            TeamDownloadDto downloadDto = new TeamDownloadDto();
            BeanUtils.copyProperties(teamRespDto , downloadDto);
            teamRespDtos.add(downloadDto);
            }


        String fileName = System.currentTimeMillis()+"队伍导出信息.xls";
        ExportExcel.exportExcel("队伍导出表" , "队伍导出表" , headers  , teamRespDtos , Constant.downloadPath+"/"+fileName,  null);
        return fileName;
    }
}
